/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2016-2026 HMC,Inc.All Rights Reserved.
 */
package com.sys.midware.redis.core;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.sys.midware.redis.config.RedisConfig;
import com.sys.midware.redis.config.RedisConfigHolder;
import com.sys.midware.redis.config.RedisConfigUtil;
import com.sys.midware.redis.config.RunModeEnum;
import com.sys.midware.redis.core.handler.RedisHandler;
import com.sys.midware.redis.core.handler.RedisHandlerCluster;
import com.sys.midware.redis.core.handler.RedisHandlerSingle;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ShardedJedis;

/**
 * 
 * <b>Description：</b> redis-handler工厂 <br/>
 * <b>ClassName：</b> RDBFactory <br/>
 * <b>@author：</b> jackyshang <br/>
 * <b>@date：</b> 2016年8月22日 下午3:02:29 <br/>
 * <b>@version: </b>  <br/>
 */
public class RedisFactory {
    
    protected static Logger logger = Logger.getLogger(RedisFactory.class);
    private static RedisFactory instance;
    private RedisFactory(){}
    /**
     * 获取单例工厂
     * 
     * @return
     * @throws Exception
     */
    public static RedisFactory getInstance()  {
        if (instance != null)
            return instance;

        synchronized (RedisFactory.class) {
            if (instance == null) {
                instance = new RedisFactory();
            }

            return instance;
        }
    }
    
    
    public RedisHandler getHandler(){
        RedisConfigUtil.initConfig();
        RedisConfig config =RedisConfigHolder.get();
        if(config!=null && RunModeEnum.CLUSTER.getValue().equalsIgnoreCase(config.getRunMode())){
            return RedisHandlerCluster.getInstance();
        }else {
            return RedisHandlerSingle.getInstance();
        }
    }
    
    public synchronized Jedis getClient(){
        RedisHandlerSingle handler=(RedisHandlerSingle)getHandler();
        return handler.getClient();
    }
    
    public synchronized  JedisCluster getClient4Cluster(){
        RedisHandlerCluster handler=(RedisHandlerCluster)getHandler();
        return handler.getClient4Cluster();
    }
    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public static synchronized void close(final ShardedJedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
    
    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public static synchronized void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
    
    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public static synchronized void close(final JedisCluster jedis) {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (IOException e) {
                logger.error("关闭jedis cluster 异常",e);
            }
        }
    }
}
